<template>
	<el-dialog v-model="visible" :title="title" :close-on-click-modal="false" draggable>
		<!-- <template #body> -->
		<el-form :disabled="formDisabled" ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px" @keyup.enter="submitHandle()">
			<el-form-item prop="source" label="用户来源">
				<el-input v-model="dataForm.source" placeholder="用户来源" disabled></el-input>
			</el-form-item>
			<el-form-item prop="orgId" label="所属机构">
				<el-input v-model="orgName" placeholder="所属机构" disabled></el-input>
				<!-- <el-tree-select
					v-model="dataForm.orgId"
					:data="orgList"
					check-strictly
					value-key="id"
					:props="{ label: 'name', children: 'children' }"
					:disabled="true"
					style="width: 100%"
				/> -->
			</el-form-item>
			<el-form-item prop="realName" label="姓名">
				<el-input v-model="dataForm.realName" placeholder="姓名"></el-input>
			</el-form-item>
			<el-form-item prop="username" label="用户名">
				<el-input v-model="dataForm.username" placeholder="用户名"></el-input>
			</el-form-item>
			<el-form-item prop="mobile" label="手机号">
				<el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
			</el-form-item>
			<el-form-item prop="idCard" label="身份证号">
				<el-input v-model="dataForm.idCard" placeholder="身份证号"></el-input>
			</el-form-item>
			<el-form-item prop="workerCategory" label="职工类别名称">
				<fast-select v-model="dataForm.workerCategory" dict-type="worker_category" placeholder="职工类别名称" clearable></fast-select>
			</el-form-item>
			<el-form-item prop="ward" label="病区">
				<el-input v-model="dataForm.ward" placeholder="病区"></el-input>
			</el-form-item>
			<el-form-item prop="roleIdList" label="关联角色">
				<el-select v-model="dataForm.roleIdList" multiple placeholder="关联角色" style="width: 80%">
					<el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"></el-option>
				</el-select>
				<el-button link type="primary" @click="rulesDataList">权限复用</el-button>
			</el-form-item>
			<el-form-item prop="status" label="状态">
				<fast-radio-group v-model="dataForm.status" dict-type="enable_disable"></fast-radio-group>
			</el-form-item>
			<el-form-item prop="department" label="科室">
				<el-input v-model="dataForm.department" placeholder="请输入科室"></el-input>
			</el-form-item>
			<el-form-item prop="remark" label="备注">
				<el-input v-model="dataForm.remark" placeholder="请输入备注"></el-input>
			</el-form-item>
		</el-form>
		<!-- </template> -->
		<template #footer v-if="!formDisabled">
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" :loading="loading" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
	<el-dialog v-model="rulesVisible" title="权限复用">
		<div style="min-height: 500px">
			<el-table v-loading="state.dataListLoading" :data="state.dataList" border style="width: 100%:" @selection-change="selRulesChangeHandle">
				<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
				<el-table-column label="序号" type="index" width="60" align="center"> </el-table-column>
				<el-table-column prop="username" label="用户名" header-align="center" align="center"></el-table-column>
				<el-table-column prop="realName" label="姓名" header-align="center" align="center"></el-table-column>
				<el-table-column prop="roleNameList" label="角色" header-align="center" align="center">
					<template #default="scope">
						<span v-for="(item, index) in scope.row.roleNameList" :key="index">
							{{ item }}
							<i v-if="index !== scope.row.roleNameList.length - 1">、</i>
						</span>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				:current-page="state.page"
				:page-sizes="state.pageSizes"
				:page-size="state.limit"
				:total="state.total"
				layout="total, sizes, prev, pager, next, jumper"
				@size-change="sizeChangeHandle"
				@current-change="currentChangeHandle"
			>
			</el-pagination>
		</div>
		<template #footer>
			<el-button @click="rulesVisible = false">取消</el-button>
			<el-button type="primary" @click="submitRulesHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import store from '@/store'
import { useCrud } from '@/hooks'
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus/es'
import { useOrgListApi } from '@/api/sys/orgs'
import { useUserApi, useUserSubmitApi } from '@/api/sys/user'
import { usePostListApi } from '@/api/sys/post'
import { useRoleListApi } from '@/api/sys/role'
import { IHooksOptions } from '@/hooks/interface'
import service from '@/utils/request'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const postList = ref<any[]>([])
const roleList = ref<any[]>([])
const orgList = ref([])
const dataFormRef = ref()

const rulesVisible = ref(false)

const orgName = JSON.parse(sessionStorage.getItem('userInfo')).orgName

const state: IHooksOptions = reactive({
	dataListUrl: '/sys/user/page',
	queryForm: {
		projectId: 1,
		orgId: ''
	},
	dataListSelections: []
})

const dataForm = reactive({
	id: '',
	source: '平台创建',
	username: '',
	realName: '',
	orgId: JSON.parse(sessionStorage.getItem('userInfo')).orgId,
	orgName: '',
	password: '888888',
	// gender: 0,
	// email: '',
	mobile: '',
	idCard: '',
	workerCategory: '',
	ward: '',
	roleIdList: [] as any[],
	postIdList: [] as any[],
	status: 1,
	department: '',
	remark: ''
})

const loading = ref(false)

const title = ref('')

const formDisabled = ref(false)

const init = (id?: number, type?: string) => {
	// console.log(store.userStore.user.orgId)
	visible.value = true
	dataForm.id = ''

	if (type === 'details') {
		formDisabled.value = true
		title.value = '详情'
	} else {
		formDisabled.value = false
		title.value = '编辑'
	}

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}

	// id 存在则为修改
	if (id) {
		getUser(id)
	} else {
		title.value = '新建'
		// dataForm.orgId = store.userStore.user.orgId
		dataForm.orgId = JSON.parse(sessionStorage.getItem('userInfo')).orgId
		dataRules.value.username = [
			{ required: true, message: '必填项不能为空', trigger: 'blur' },
			{ pattern: /^((?!@).)*$/, message: '用户名不能包含@符号', trigger: 'blur'}
		]
	}

	// getOrgList()
	// getPostList()
	getRoleList()
}

// 获取岗位列表
const getPostList = () => {
	return usePostListApi().then(res => {
		postList.value = res.data
	})
}

// 获取角色列表
const getRoleList = () => {
	let orgIda = JSON.parse(sessionStorage.getItem('userInfo')).orgId
	let param = '?orgId=' + orgIda
	return useRoleListApi(param).then(res => {
		roleList.value = res.data
	})
}

// 获取机构列表
const getOrgList = () => {
	return useOrgListApi().then(res => {
		orgList.value = res.data
	})
}

// 获取信息
const getUser = (id: number) => {
	let orgIda = JSON.parse(sessionStorage.getItem('userInfo')).orgId
	let param = id + '/' + orgIda
	useUserApi(param).then(res => {
		Object.assign(dataForm, res.data)
		if (res.data.source === 'HIS同步') {
			dataRules.value.username = [
				{ required: true, message: '必填项不能为空', trigger: 'blur' }
			]
		} else {
			dataRules.value.username = [
				{ required: true, message: '必填项不能为空', trigger: 'blur' },
				{ pattern: /^((?!@).)*$/, message: '用户名不能包含@符号', trigger: 'blur'}
			]
		}
	})

	console.log(dataForm)
}

const dataRules = ref({
	username: [
		{ required: true, message: '必填项不能为空', trigger: 'blur' },
		{ pattern: /^((?!@).)*$/, message: '用户名不能包含@符号', trigger: 'blur'}
	],
	realName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	mobile: [
		{ required: true, message: '必填项不能为空', trigger: 'blur' },
		{ pattern: /^1[3456789]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的联系方式', trigger: 'blur' }
	],
	orgId: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	// roleIdList: [{ required: true, message: '必填项不能为空', trigger: 'change' }],
	status: [{ required: true, message: '必填项不能为空', trigger: 'change' }]
})

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			loading.value = false
			return false
		}

		loading.value = true
		useUserSubmitApi(dataForm)
			.then(res => {
				if (res.msg !== 'success') {
					ElMessageBox.confirm('是否需要重复创建用户?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
						.then(() => {
							service.post('/sys/user/reuseSave', dataForm).then(res => {
								ElMessage.success({
									message: '操作成功',
									duration: 500,
									onClose: () => {
										loading.value = false
										visible.value = false
										emit('refreshDataList')
									}
								})
							})
						})
						.catch(() => {
							loading.value = false
						})
				} else {
					ElMessage.success({
						message: '操作成功',
						duration: 500,
						onClose: () => {
							loading.value = false
							visible.value = false
							emit('refreshDataList')
						}
					})
				}
			})
			.catch(() => {
				loading.value = false
			})
	})
}

// 获取用户权限
const rulesDataList = () => {
	rulesVisible.value = true
	state.queryForm.orgId = JSON.parse(sessionStorage.getItem('userInfo')).orgId
	getDataList()
}

const selRulesData = ref([])
const selRulesChangeHandle = (data: any[]) => {
	data.forEach(item => {
		if (item.roleIdList) {
			item.roleIdList.forEach((roleId: number) => {
				selRulesData.value.push(roleId)
			})
		}
	})
}

const submitRulesHandle = () => {
	const new_data = dataForm.roleIdList.concat(selRulesData.value)
	// dataForm.roleIdList.concat(selRulesData.value)

	const new_data_set = Array.from(new Set(new_data))
	dataForm.roleIdList = new_data_set
	rulesVisible.value = false
}

const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle } = useCrud(state)

defineExpose({
	init
})
</script>
